﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace DoubleH.Utility
{
    public class WindowsUtility
    {
        private const string AutoRunKey = "Software\\Microsoft\\Windows\\CurrentVersion\\Run";
        /// <summary>
        /// 设置程序随系统启动
        /// </summary>
        /// <param name="bAutoStart"></param>
        public static void SetStartWithWindows( bool bAutoStart,string exeFullName)
        {
            try
            {
                if (bAutoStart)
                    Registry.SetValue("HKEY_CURRENT_USER\\" + AutoRunKey,Path.GetFileNameWithoutExtension(exeFullName),
                       exeFullName, RegistryValueKind.String);
                else
                {
                    RegistryKey kRun = Registry.CurrentUser.OpenSubKey(AutoRunKey, true);
                    kRun.DeleteValue(Path.GetFileNameWithoutExtension(exeFullName));
                }
            }
            catch {  }
        }
        /// <summary>
        /// 注册热键
        /// </summary>
        /// <param name="nId">id</param>
        /// <param name="kKey">键代码</param>
        /// <returns>bool</returns>
        public static bool RegisterHotKey(IntPtr handle, int nId, Keys kKey)
        {
            if (kKey == Keys.None) return false;

            uint uMod = 0;
            if ((kKey & Keys.Shift) != Keys.None) uMod |= WinAPI.MOD_SHIFT;
            if ((kKey & Keys.Alt) != Keys.None) uMod |= WinAPI.MOD_ALT;
            if ((kKey & Keys.Control) != Keys.None) uMod |= WinAPI.MOD_CONTROL;

            uint vkCode = (uint)(kKey & Keys.KeyCode);

            UnregisterHotKey(handle, nId);

            try
            {
                    if (WinAPI.RegisterHotKey(handle, nId, uMod, vkCode))
                        return true;
            }
            catch { }
            return false;
        }
        /// <summary>
        /// 取消注册热键
        /// </summary>
        /// <param name="nId">id</param>
        /// <returns>bool</returns>
        public static bool UnregisterHotKey(IntPtr handle, int nId)
        {
            try
            {
                bool bResult  = WinAPI.UnregisterHotKey(handle, nId);

                return bResult;
            }
            catch { }

            return false;
        }
    }

    public class WinAPI
    {
        public const uint MOD_ALT = 1;
        public const uint MOD_CONTROL = 2;
        public const uint MOD_SHIFT = 4;
        public const uint MOD_WIN = 8;

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool RegisterHotKey(IntPtr hWnd, int id, uint fsModifiers, uint vk);

        [DllImport("user32.dll")]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool UnregisterHotKey(IntPtr hWnd, int id);
    }
}